package com.huizhan.web.controller;

import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.domain.Sort.*;
import io.swagger.annotations.*;
import java.util.*;

import javax.servlet.http.*;

import com.huizhan.web.dao.*;
import com.huizhan.web.model.*;
import com.huizhan.web.view.*;

@Api(tags = "Distribute",description = "证件分发")
@RestController
public class DistributeController {
    
    @Autowired
    private DistributeDao dao;
   
    @Autowired
    private DocumentTypeDao daoType;
   
    @Autowired
    private DocumentDao daoDoc;
   
    @Autowired
    private DocumentRecordDao recordDao;
    
    @Autowired
    private ProjectDao projectDao;

    /**
     * 创建自己的证件
     * @param id
     * @return
     */
    @ApiOperation(value = "创建自己的证件")
    @RequestMapping(value =  "/api/Distribute/{id}",method = {RequestMethod.PATCH})
    public ApiResult<Document> Get(@PathVariable Long id){
        ApiResult<Document> result=new ApiResult<Document>();
        try 
        {
           Distribute distribute= dao.getOne(id);

           if(distribute!=null){

               if(daoDoc.findByDocumentTypeIdAndPhone(distribute.getDocumentTypeId(), distribute.getPhone())==null){
                    distribute.setUseNumber(distribute.getUseNumber()+1);
                    
                    dao.save(distribute);
                    
                    Document document=new Document();
                    String no= TenpayUtil.randomNumber(8);

                    while(daoDoc.countByProjectIdAndCode(distribute.getProjectId(), no)>0){
                        no= TenpayUtil.randomNumber(8);
                    }

                    DocumentRecord record=new DocumentRecord();

                    record.setCreateDate(new Date());
                    record.setDistributeId(distribute.getDistributeId());
                    record.setDocumentTypeId(distribute.getDocumentTypeId());
                    record.setName(distribute.getName());
                    record.setNumber(-1L);
                    record.setPhone(distribute.getPhone());
                    record.setProjectId(distribute.getProjectId());
                    record.setTypeName(distribute.getTypeName());
                    record.setUrl(distribute.getName()+"给自己创建了一个证件");

                    recordDao.save(record);

                    document.setCode(no);
                    document.setIdNumber(distribute.getPhone());
                    document.setTypeName(distribute.getTypeName());
                    document.setDistributeId(distribute.getDistributeId());
                    document.setPhone(distribute.getPhone());
                    document.setName(distribute.getName());
                    document.setProjectId(distribute.getProjectId());
                    document.setDocumentTypeId(distribute.getDocumentTypeId());
                    document.setCreateDate(new Date());

                    daoDoc.save(document);
               }else{
                    result.setHasError(true);
                    result.setMessage("您已经创建自己的证件");
               }
           }else{
                result.setHasError(true);
                result.setMessage("参数错误");
           }
        }catch(Exception e){
            result.setHasError(true);
            result.setMessage(e.getMessage());
        }
        return result;
    }

    /**
     * 删除证件分发信息
     * @param id 证件分发ID
     * @return api结果
     */
    @ApiOperation(value = "删除证件分发信息")
    @RequestMapping(value =  "/api/Distribute/{id}",method = {RequestMethod.DELETE})
    public ApiResult<Object> Delete(@PathVariable  Long id){
        ApiResult<Object> result=new ApiResult<Object>();
        try 
        {
            daoDoc.deleteByDistributeId(id);
            dao.deleteById(id);
        }catch(Exception e){
            result.setHasError(true);
            result.setMessage(e.getMessage());
        }
        return result;
    }
    
    private Boolean SendSMS(Project project,Distribute model,Long count, HttpServletRequest request){

        boolean b=false;

        try {
            String data="{\"account\":\"dh81653\",\"password\":\""+
            TenpayUtil.MD5("e3YiG73c").toLowerCase()
            +"\",\"msgid\":\""
            +(UUID.randomUUID().toString())
            +"\",\"phones\":"
            +model.getPhone()
            +",\"content\":\""
            +model.getName()
            +"您收到"
            +project.getName()
            +"电子证件"
            +(count)
            +"张 ";

            /*if(model.getTotal()==count&&count<6){
                for (Document Document : list) {
                    data+=request.getScheme() + "://" + request.getServerName()+"/"+Document.getDocumentTypeId()+","+Document.getCode()+"\\n";
                }
            }else{*/
                data+=request.getScheme() + "://" + request.getServerName()+"/d/"+model.getDistributeId();
            //}

            data+="\",\"sign\":\"【"
            +project.getSignName()
            +"】\",\"subcode\":\"\",\"sendtime\":\"\"}";

            TenpayHttpClient httpClient = new TenpayHttpClient();  

            httpClient.callHttpPost("http://www.dh3t.com/json/sms/Submit", data);
            String  resContent = httpClient.getResContent();

            if(resContent.contains("提交成功")){
                b=true;
            }
        } catch (Exception e) {
             b=false;
        }
       return b;
    }

    /**
     * 查询证件分发集合
     * @param model 账号信息
     * @return api结果
     */
    @ApiOperation(value = "查询证件分发集合")
    @RequestMapping(value =  "/api/Distribute/Search",method = {RequestMethod.POST})
    public ApiResult<List<Distribute>> Search(@RequestBody PageTicketComplimentary model){
         ApiResult<List<Distribute>> result=new ApiResult<List<Distribute>>();
         
        try
        {    
            PageRequest pageable = PageRequest.of(model.getPageIndex(),model.getPageSize(),Direction.DESC,"Distribute_Id") ;            
            Page<Distribute> page = dao.findByWhere(model.getName(),model.getPhone(),model.getProjectId(),model.getLevel(),pageable);
            result.setData(page.getContent());
            result.setTotal(page.getTotalElements());
        }catch(Exception e){
            result.setHasError(true);
            result.setMessage(e.getMessage());
        }
        
        return result;
    }

    /**
     * 修改证件分发信息
     * @param id 证件分发ID
     * @param model 证件分发信息
     * @return api结果
     */
    @ApiOperation(value = "证件分发")
    @RequestMapping(value =  "/api/Distribute/{id}",method = {RequestMethod.PUT})
    public ApiResult<Distribute> Edit(@PathVariable Long id,@RequestBody Distribute model,HttpServletRequest request){
        ApiResult<Distribute> result=new ApiResult<Distribute>();
        try
        {
            Optional<Distribute> Document=dao.findById(id);
            Long count=model.getTotal();

            if(Document.isPresent()){
                if(Document.get().getUseNumber()==null){
                    Document.get().setUseNumber(0L);
                }
                if(Document.get().getTotal()-Document.get().getUseNumber()<count){
                    result.setHasError(true);
                    result.setMessage("证件分发数量不能大于:"+(Document.get().getTotal()-Document.get().getUseNumber()));
                }else{
                    Document.get().setUseNumber(Document.get().getUseNumber()+count);

                    dao.save(Document.get());

                    Distribute complimentary=dao.findByDocumentTypeIdAndPhone(Document.get().getDocumentTypeId(), model.getPhone());

                    DocumentRecord record=new DocumentRecord();

                    if(complimentary==null){
                        model.setLevel(Document.get().getLevel()==null?1:Document.get().getLevel()+1);
                        model.setParentId(Document.get().getDistributeId());
                        model.setDocumentTypeId(Document.get().getDocumentTypeId());
                        model.setCreateDate(new Date());
                        model.setProjectId(Document.get().getProjectId());
                        model.setTypeName(Document.get().getTypeName());
                        model.setUseNumber(0L);
                        dao.save(model);
                        record.setDistributeId(model.getDistributeId());
                        complimentary=model;
                    }else{
                        complimentary.setTotal(complimentary.getTotal()+count);
                        dao.save(complimentary);
                        record.setDistributeId(complimentary.getDistributeId());
                    }

                    record.setProjectId(Document.get().getProjectId());
                    record.setPhone(model.getPhone());
                    record.setName(model.getName());
                    record.setCreateDate(new Date());
                    record.setNumber(model.getTotal());
                    record.setDocumentTypeId(Document.get().getDocumentTypeId());
                    record.setTypeName(Document.get().getTypeName());
                    record.setUrl(model.getPhone()+"("+model.getName()+")收到"+Document.get().getPhone()+"("+Document.get().getName()+")"+"证件分发"+model.getTotal()+"张");
                    recordDao.save(record);

                    record=new DocumentRecord();
                    record.setTypeName(Document.get().getTypeName());
                    record.setCreateDate(new Date());
                    record.setProjectId(Document.get().getProjectId());
                    record.setDocumentTypeId(Document.get().getDocumentTypeId());
                    record.setUrl("从"+Document.get().getPhone()+"("+Document.get().getName()+")"+"分发给"+model.getPhone()+"("+model.getName()+")"+model.getTotal()+"张证件");
                    record.setDocumentRecordId(null);
                    record.setDistributeId(id);
                    record.setPhone(Document.get().getPhone());
                    record.setName(Document.get().getName());
                    record.setNumber(-model.getTotal());                    
                    recordDao.save(record);
                    
                    Project project=projectDao.getOne(Document.get().getProjectId());

                    SendSMS(project,complimentary,count,request);
                }
            }else{
                result.setHasError(true);
                result.setMessage("参数错误");
            }
        }catch(Exception e){
            result.setHasError(true);
            result.setMessage(e.getMessage());
        }
        return  result;
    }


    /**
     * 添加证件分发信息
     * @param model 证件分发信息
     * @return api结果
     */
    @ApiOperation(value = "更新证件分发信息")
    @RequestMapping(value =  "/api/Distribute/",method = {RequestMethod.PATCH})
    public ApiResult<Distribute> Edit(@RequestBody Distribute model,HttpServletRequest request){
         ApiResult<Distribute> result=new ApiResult<Distribute>();
        try
        {
            Distribute Distribute = dao.findByDocumentTypeIdAndPhone(model.getDocumentTypeId(),model.getPhone());

            if(Distribute==null){
                result.setHasError(true);
                result.setMessage("手机号码不存在");
            }  else if  (model.getProjectId()==""){
                result.setHasError(true);
                result.setMessage("项目ID不能为空");
            }  else if(model.getTotal()<=0){
                result.setHasError(true);
                result.setMessage("证件数必须大于0");
            } else{ 
                DocumentType type = daoType.getOne(model.getDocumentTypeId());
                Project project=projectDao.getOne(model.getProjectId());

                model.setUseNumber(Distribute.getUseNumber());
                model.setLevel(Distribute.getLevel());
                model.setCreateDate(new Date());
                model.setTypeName(type.getName());
                model.setDistributeId(Distribute.getDistributeId());

                if(model.getTotal()>Distribute.getTotal()){
                    SendSMS(project, model,model.getTotal()-Distribute.getTotal(),request);
                }else if(model.getTotal()<Distribute.getTotal()){

                }

                DocumentRecord record=new DocumentRecord();
                record.setDistributeId(model.getDistributeId());
                record.setTypeName(type.getName());
                record.setCreateDate(new Date());
                record.setProjectId(type.getProjectId());
                record.setDocumentTypeId(type.getDocumentTypeId());
                record.setUrl("系统给"+model.getPhone()+"("+model.getName()+")"+(model.getTotal()-Distribute.getTotal())+"张证件");
                record.setPhone(model.getPhone());
                record.setName(model.getName());
                record.setNumber(model.getTotal()-Distribute.getTotal());                    
                recordDao.save(record);

                dao.save(model);

                result.setData(model);
            }
        }catch(Exception e){
            result.setHasError(true);
            result.setMessage(e.getMessage());
        }
        return result;
    }

    /**
     * 添加证件分发信息
     * @param model 证件分发信息
     * @return api结果
     */
    @ApiOperation(value = "添加证件分发信息")
    @RequestMapping(value =  "/api/Distribute/",method = {RequestMethod.POST})
    public ApiResult<Distribute> Add(@RequestBody Distribute model,HttpServletRequest request){
         ApiResult<Distribute> result=new ApiResult<Distribute>();
        try
        {
            if(model.getProjectId()==null||model.getProjectId()==""){
                result.setHasError(true);
                result.setMessage("项目ID不能为空");
            }else if(model.getDocumentTypeId()==null||model.getDocumentTypeId()==0){
                result.setHasError(true);
                result.setMessage("证件类型ID不能为空");
            }else if(dao.findByDocumentTypeIdAndPhone(model.getDocumentTypeId(),model.getPhone())!=null){
                result.setHasError(true);
                result.setMessage("手机号码已存在");
            }else if(model.getTotal()<1){
                result.setHasError(true);
                result.setMessage("证件数必须大于0");
            }else{
                DocumentType type= daoType.getOne(model.getDocumentTypeId());
                Project project=projectDao.getOne(model.getProjectId());
                model.setCreateDate(new Date());
                model.setTypeName(type.getName());
                model.setLevel(0L);
                dao.save(model);

                DocumentRecord record=new DocumentRecord();
                record.setDistributeId(model.getDistributeId());
                record.setTypeName(type.getName());
                record.setCreateDate(new Date());
                record.setProjectId(type.getProjectId());
                record.setDocumentTypeId(type.getDocumentTypeId());
                record.setUrl("系统给"+model.getPhone()+"("+model.getName()+")"+model.getTotal()+"张证件");
                record.setPhone(model.getPhone());
                record.setName(model.getName());
                record.setNumber(model.getTotal());                    
                recordDao.save(record);
                SendSMS(project, model,model.getTotal(), request);
                result.setData(model);
            }
        }catch(Exception e){
            result.setHasError(true);
            result.setMessage(e.getMessage());
        }
        return result;
    }
}